<script type="text/ecmascript-6">
    /**
     * Created by wcz on 2017/3/27.
     */
    const prefix = 'http://oo6sy4zq6.bkt.clouddn.com/'
    const smallExt = '?imageView2/2/w/400/h/1200/q/75'
    const previewExt = '?imageView2/2/w/900/h/3000/q/75'
    const thmDownloadExt = '?imageView2/2/w/1600/h/5000'
    const TOKEN = window.__ToKeN__

    export default {
        data () {
            return {
                loading: false,
                currentPage: 1,
                total: 1,
                pageSize: 50,
                photographers: [],
                checkList: [],
                checkAll: false,
                currentPhotographer: 0,
                currentPhotographerCode: '',
                photoList: [],
                single: false,
                uploadDialogVisible: false,
                uploadDisabled: false,
                uploadDialogBtnTxt: '关闭对话框',
                // 预览图片
                pointSrc: '',
                viewVisible: false,
                timer: null,
            }
        },
        computed: {
            headers () {
                return {
                    'X-CSRFToken': this.user.token
                }
            },
            user () {
                return this.$store.state.user
            },
            isAdmin () {
                return this.user.role === 4
            },
            filter () {
                return this.$route.params.filter
            },
            actID () {
                return this.$route.params.actID
            },
            isJingxiu () {
                return this.filter === 'truing'
            },
            isThm () {
                return this.filter === 'thumbnail'
            },
            isOri () {
                return this.filter === 'raw'
            },
            uploadAPI () {
                return `${apiHost}/activities/${this.actID}/truing_pictures/`
            }
        },
        async mounted () {
            await this.getCameraList()
            this.currentPhotographer = this.photographers[0].value
            this.currentPhotographerCode = this.photographers[0].name
            await this.getList()
            this.timer = setInterval(() => {
                this.getList(this.currentPage)
            }, 3500)
        },
        beforeDestroy () {
            clearInterval(this.timer)
        },
        methods: {
            async getList (currentPage = 1) {
                let postData = {
                    page: currentPage,
                }
                if (!this.isThm) {
                    postData.occupy = this.isOri && !this.isJingxiu
                }
                this.loading = true
                let res = !this.isJingxiu
                    ? await this.api.getBasePhotoList(postData, this.actID, this.currentPhotographer)
                    : await this.api.getJXPhotoList(currentPage, this.actID)
                if (res.success) {
                    this.photoList = res.data.results.map(e => {
                        let ele = e
                        let photo = !this.isJingxiu ? e.file_original : e.file
                        e.smallPic = !this.isJingxiu ? prefix + photo + smallExt : photo + smallExt
                        e.previewPic = !this.isJingxiu ? prefix + photo + previewExt : photo + previewExt
                        e.downloadSrc = this.isThm
                            ? prefix + photo + thmDownloadExt
                            : (!this.isJingxiu ? prefix + photo : photo)
                        ele.isSel = e.occupy
                        if (!this.isJingxiu) {
                            ele.serialNumber = e.file_compressed.split('/')[e.file_compressed.split('/').length - 1]
                        }
                        ele.occupy = (e.retoucher !== null)
                        ele.retoucherName = e.retoucher ? e.retoucher.name : '无修图师'
                        return ele
                    })

                    this.total = res.data.count
                }
                this.loading = false
            },
            async getCameraList () {
                let res = await this.api.getCameraList(this.actID)
                if (res.success) {
                    let p = new Map() // 'this.photographers'
                    let t = res.data.results.map(e => {
                        return {
                            name: e.invite_code,
                            value: e.id
                        }
                    })
                    this.photographers = t.filter(e => !p.has(e.name) && p.set(e.name, 1))
                }
            },
            handleFilterChange (val) {
                this.getList()
            },
            changePhotographer (id, name) {
                this.currentPhotographer = id
                this.currentPhotographerCode = name
                this.getList()
            },
            viewImg (src) {
                this.pointSrc = src
                this.viewVisible = true
            },
            exitView () {
                this.viewVisible = false
            },
            async downloadThis (src, photo) {
                let downloadStatus = this.isThm ? photo.downloaded_compressed : photo.downloaded_original
                let request = this.isThm ? 'thmDownload' : 'oriDownload'
                if (!downloadStatus) {
                    await this.api[request](this.actID, this.currentPhotographer, photo.id)
                    let tag = document.createElement('a')
                    tag.href = src
                    tag.setAttribute('download', src)
                    tag.click()
                    this.$Message.success('下载成功！')
                    this.getList()
                } else {
                    this.$Modal.confirm({
                        title: '确认下载',
                        content: '<p>这张照片已经被人下载过了，还要下载吗？</p>',
                        onOk: () => {
                            let tag = document.createElement('a')
                            tag.href = src
                            tag.setAttribute('download', src)
                            tag.click()
                        }
                    });
                }
            },
            async addThis (id) {
                let res = await this.api.addPhoto(this.actID, this.currentPhotographer, id)
                if (res.success) {
                    this.getList()
                    this.$Message.success('选择成功！')
                }
            },
            showUploadDialog () {
                this.uploadDialogVisible = true
            },
            hideUploadDialog () {
                this.uploadDialogVisible = false
            },
            uploading () {
                this.uploadDisabled = true
                this.uploadDialogBtnTxt = '上传中，请勿关闭'
            },
            uploadFinish () {
                this.uploadDisabled = false
                this.uploadDialogBtnTxt = '关闭对话框'
            },
            uploadFailed () {
                this.uploadDisabled = false
                this.uploadDialogBtnTxt = '关闭对话框'
            },
            changePage (pageIdx) {
                this.currentPage = pageIdx
                this.getList(pageIdx)
            }
        },
        watch: {
            '$route.params': 'handleFilterChange'
        }
    };
</script>

<template>
  <div class="detail block">
    <div class="detail__tab" layout="row center-left" :class="[isJingxiu ? 'p' : '']">
      <!--<div-->
      <!--class="detail__tab-item"-->
      <!--:class="[currentPhotographer == 0 ? 'active': '']"-->
      <!--@click="changePhotographer(0)"-->
      <!--&gt;全部-->
      <!--</div>-->
      <div
              v-if="!isJingxiu"
              v-for="p in photographers"
              class="detail__tab-item"
              :class="[currentPhotographer == p.value ? 'active': '']"
              @click="changePhotographer(p.value, p.name)"
      >{{p.name}}




      </div>
      <!-- 分页-->
      <Page self="right" :page-size="pageSize" :current="currentPage" :total="total" @on-change="changePage"></Page>
      <Button @click="showUploadDialog" v-if="!isAdmin && isJingxiu" type="primary" icon="android-upload" self="right">
        上传图片




      </Button>
    </div>
    <!-- 精修片工具栏-->
    <div class="detail__tool" layout="row center-left" v-if="false">
      <Checkbox v-model="single">全选</Checkbox>
      <Button type="primary" class="pl10">下载选中图片</Button>
      <Button class="pl10">删除选中图片</Button>
    </div>

    <!-- 图片盒子-->
    <section class="detail__photo-box cf" :class="[isJingxiu ? 'truing': '']">
      <!-- 图片列表-->
      <div v-if="total !== 0" v-for="(photo, index) in photoList" :key="index" class="detail__photo">
        <div class="detail__header" v-if="!isJingxiu">
          <Tag color="blue" type="dot" v-if="photo.occupy">已选择</Tag>
          <Tag type="dot" color="yellow" v-if="isThm ? photo.downloaded_compressed : photo.downloaded_original">已下载




          </Tag>
        </div>
        <div class="detail__header" layout="row center-right" v-else style="display: none;">
          <Checkbox v-model="single">选中此图片</Checkbox>
        </div>
        <!-- 图片-->
        <div class="detail__body" @click="viewImg(photo.previewPic)"
             :style="{backgroundImage: 'url(' + photo.smallPic + ')'}"></div>
        <!-- 图片名字-->
        <div class="detail__img-name">{{photo.serialNumber}}</div>
        <!-- 操作者信息-->
        <div class="detail__bottom">
          <div class="detail__belong">
            <Icon type="camera"></Icon>
            <span class="detail__name"> {{currentPhotographerCode}}</span>
          </div>
          <div class="detail__belong" v-if="isJingxiu || isOri">
            <Icon type="android-hand"></Icon>
            <span class="detail__name"> {{photo.retoucherName}}</span>
          </div>
        </div>
        <!-- 下载-->
        <div class="detail__download" layout="row center-center">
          <div v-if="!photo.occupy && !isJingxiu" class="detail__button" layout="row center-center" @click="addThis(photo.id)"
               style="margin-right: 5px;">
            <Icon type="plus"></Icon>
          </div>
          <div class="detail__button" layout="row center-center" @click="downloadThis(photo.downloadSrc, photo)">
            <Icon type="android-arrow-down"></Icon>
          </div>
        </div>
      </div>
      <div v-if="total === 0" class="hx__empty">
        <Icon type="images"></Icon>
        暂无照片






      </div>
    </section>
    <!-- 上传图片框-->
    <Modal
            v-model="uploadDialogVisible"
            title="上传照片"
            @on-ok="getList"
    >
      <Upload
              multiple
              type="drag"
              :data="{activity: actID}"
              :action="uploadAPI"
              :with-credentials="true"
              :headers="headers"
              :on-progress="uploading"
              :on-success="uploadFinish"
              :on-error="uploadFailed"
              accept="image/jpg,image/jpeg"
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>点击或将文件拖拽到这里上传（可批量）</p>
        </div>
      </Upload>
      <div slot="footer">
        <Button :disabled="uploadDisabled" :loading="uploadDisabled" type="primary" size="large" long
                @click="hideUploadDialog">{{uploadDialogBtnTxt}}






        </Button>
      </div>
    </Modal>
    <!-- 图片预览-->
    <div v-show="viewVisible" class="detail__preview" @click="exitView" layout="row center-center">
      <p class="detail__arrow left" @click="other(-1)"></p>
      <p class="detail__arrow right" @click="other(1)"></p>
      <p class="detail__preview-info"></p>
      <img :src="pointSrc" class="detail__preview-img">
      <p class="detail__preview-action"></p>
    </div>
  </div>
</template>